#include "GPURenderTarget.h"


#include "Render/VulkanContext.h"



CGPURenderTarget::~CGPURenderTarget()
{
    if(IsInitialized())
    {
        Deinitialize();
    }
}

void CGPURenderTarget::Initialize(vk::Extent3D InSize, vk::Format InFormat, vk::ImageUsageFlags InUsage)
{
    Size=InSize;
    Format=InFormat;
    Usage=InUsage;

    vk::ImageCreateInfo ImageCreateInfo= vk::ImageCreateInfo()
        .setImageType(vk::ImageType::e2D)
        .setExtent(Size)
        .setMipLevels(1)
        .setArrayLayers(1)
        .setFormat(Format)
        .setUsage(Usage)
        ;

    Image=CVulkanContext::Get()->GetDevice().createImage(ImageCreateInfo);

    vk::MemoryRequirements MemoryRequirements=CVulkanContext::Get()->GetDevice().getImageMemoryRequirements(Image);

    vk::MemoryAllocateInfo MemoryAllocateInfo=vk::MemoryAllocateInfo()
        .setAllocationSize(MemoryRequirements.size)
        .setMemoryTypeIndex(CVulkanContext::Get()->GetMemoryTypeIndex(MemoryRequirements, vk::MemoryPropertyFlagBits::eDeviceLocal));

    Memory=CVulkanContext::Get()->GetDevice().allocateMemory(MemoryAllocateInfo);

    CVulkanContext::Get()->GetDevice().bindImageMemory(Image, Memory, 0);

    vk::ImageViewCreateInfo ImageViewCreateInfo=vk::ImageViewCreateInfo()
        .setImage(Image)
        .setViewType(vk::ImageViewType::e2D)
        .setFormat(Format)
        .setSubresourceRange(vk::ImageSubresourceRange()
            .setAspectMask(CVulkanContext::IsDepthFormat(Format)?vk::ImageAspectFlagBits::eDepth:vk::ImageAspectFlagBits::eColor )
            .setBaseMipLevel(0)
            .setLevelCount(1)
            .setBaseArrayLayer(0)
            .setLayerCount(1));

    View=CVulkanContext::Get()->GetDevice().createImageView(ImageViewCreateInfo);

}

void CGPURenderTarget::Deinitialize()
{
    CVulkanContext::Get()->GetDevice().destroyImageView(View);
    CVulkanContext::Get()->GetDevice().freeMemory(Memory);
    CVulkanContext::Get()->GetDevice().destroyImage(Image);
}

vk::Image CGPURenderTarget::GetImage()
{
    return Image;
}

vk::DeviceMemory CGPURenderTarget::GetMemory()
{
    return Memory;
}

vk::ImageView CGPURenderTarget::GetImageView()
{
    return View;
}
